package me.zhengjie.wechat.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import me.zhengjie.aop.log.Log;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.wechat.domain.AdvertisingType;
import me.zhengjie.wechat.domain.WechatCode;
import me.zhengjie.wechat.repository.AdvertisingTypeRepository;
import me.zhengjie.wechat.service.WechatCodeService;
import me.zhengjie.wechat.service.dto.WechatCodeDTO;
import me.zhengjie.wechat.service.dto.WechatCodeQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
* @author Jiang yunxiao
* @date 2019-11-10
*/
@Api(tags = "WechatCode管理")
@RestController
@RequestMapping("/api/wechatCode")
public class WechatCodeController {

    private final WechatCodeService wechatCodeService;
    private final AdvertisingTypeRepository advertisingTypeRepository;

    public WechatCodeController(WechatCodeService wechatCodeService, AdvertisingTypeRepository advertisingTypeRepository) {
        this.wechatCodeService = wechatCodeService;
        this.advertisingTypeRepository = advertisingTypeRepository;
    }

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('wechatCode:list')")
    public void download(HttpServletResponse response, WechatCodeQueryCriteria criteria) throws IOException {
        wechatCodeService.download(wechatCodeService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询WechatCode")
    @ApiOperation("查询WechatCode")
    @PreAuthorize("@el.check('wechatCode:list')")
    public ResponseEntity getWechatCodes(WechatCodeQueryCriteria criteria, Pageable pageable){
        Map<String,Object> map = wechatCodeService.queryAll(criteria,pageable);
        List<WechatCodeDTO> wechatCodeDTOS = (List<WechatCodeDTO>) map.get("content");
        for (WechatCodeDTO wechatCodeDTO : wechatCodeDTOS){
            List<Long> listIds = Arrays.asList(wechatCodeDTO.getAdvertisementType().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            List<AdvertisingType> advertisingTypes =  advertisingTypeRepository.findAllById(listIds);
            String[] abName = new String[advertisingTypes.size()];
               for (int i = 0; i <advertisingTypes.size() ; i++) {
                    abName[i] = advertisingTypes.get(i).getName();
            }
           // wechatCodeDTO.setAdvertisementType(StringUtils.join(abName, ","));
            JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(advertisingTypes));
            wechatCodeDTO.setAdJson(jsonArray);

        }

        Map<String,Object> maps = new HashMap<>();
        maps.put("content",wechatCodeDTOS);
        maps.put("totalElements",map.get("totalElements"));
     //   return new ResponseEntity<>(wechatCodeService.queryAll(criteria,pageable),HttpStatus.OK);
        return new ResponseEntity<>(maps,HttpStatus.OK);
    }

    @PostMapping
    @Log("新增WechatCode")
    @ApiOperation("新增WechatCode")
    @PreAuthorize("@el.check('wechatCode:add')")
    public ResponseEntity create(@Validated @RequestBody WechatCode resources){
        resources.setCreationTime(Timestamp.valueOf(LocalDateTime.now()));
        resources.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
        return new ResponseEntity<>(wechatCodeService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改WechatCode")
    @ApiOperation("修改WechatCode")
    @PreAuthorize("@el.check('wechatCode:edit')")
    public ResponseEntity update(@Validated @RequestBody WechatCode resources){
        wechatCodeService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping(value = "/{id}")
    @Log("删除WechatCode")
    @ApiOperation("删除WechatCode")
    @PreAuthorize("@el.check('wechatCode:del')")
    public ResponseEntity delete(@PathVariable Long id){
        wechatCodeService.delete(id);
        return new ResponseEntity(HttpStatus.OK);
    }
}